<template>
  <div class="encode-page">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-breadcrumb separator="/" style="margin-bottom: 20px;">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>编码转换工具</el-breadcrumb-item>
        </el-breadcrumb>
        <h2 style="margin-bottom: 20px; color: #303133;">编码转换工具</h2>
      </el-col>
    </el-row>

    <el-tabs v-model="activeTab" type="card">
      <!-- Unicode编码 -->
      <el-tab-pane label="Unicode编码" name="unicode">
        <el-card>
          <el-form :model="unicodeForm" label-width="100px">
            <el-form-item label="操作类型">
              <el-radio-group v-model="unicodeForm.mode" @change="handleUnicode">
                <el-radio label="encode">编码</el-radio>
                <el-radio label="decode">解码</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="输入内容">
              <el-input
                v-model="unicodeForm.input"
                type="textarea"
                :rows="4"
                :placeholder="unicodeForm.mode === 'encode' ? '请输入要编码的文本' : '请输入要解码的Unicode字符串'"
                @input="handleUnicode"
              />
            </el-form-item>
            <el-form-item label="输出结果">
              <el-input
                v-model="unicodeForm.output"
                type="textarea"
                :rows="4"
                readonly
                :placeholder="unicodeForm.mode === 'encode' ? 'Unicode编码结果' : '解码结果'"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="copyToClipboard(unicodeForm.output)">
                复制结果
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- Unix时间戳 -->
      <el-tab-pane label="Unix时间戳" name="timestamp">
        <el-card>
          <!-- 当前Unix时间戳显示 -->
          <div class="timestamp-section">
            <h3>现在的Unix时间戳 (Unix timestamp)是:</h3>
            <div class="current-timestamp" style="display: flex; align-items: center;">
              <el-input v-model="timestampForm.current" readonly class="timestamp-input" style="margin-right: 6px"/>
              <el-button @click="startTimestampUpdate" :type="timestampForm.isRunning ? 'danger' : 'primary'">
                {{ timestampForm.isRunning ? '停止' : '开始' }}
              </el-button>
              <el-button @click="refreshTimestamp" type="primary">刷新</el-button>
              <el-button @click="copyCurrentTimestamp" type="success">复制</el-button>
            </div>
          </div>

          <!-- Unix时间戳转日期时间 -->
          <div class="timestamp-section">
            <h3>Unix时间戳 (Unix timestamp)</h3>
            <div class="conversion-row">
              <el-input v-model="timestampForm.timestampInput" placeholder="请输入Unix时间戳" />
              <el-select v-model="timestampForm.timestampUnit" style="width: 80px">
                <el-option label="秒" value="seconds" />
                <el-option label="毫秒" value="milliseconds" />
              </el-select>
              <el-button @click="convertTimestampToDate" type="primary">转换</el-button>
              <el-input v-model="timestampForm.timestampResult" readonly placeholder="转换结果" />
            </div>
          </div>

          <!-- 日期时间转Unix时间戳（简化版） -->
          <div class="timestamp-section">
            <h3>时间 (年/月/日 时:分:秒)</h3>
            <div class="conversion-row">
              <el-input v-model="timestampForm.dateTimeInput" placeholder="请输入日期时间，如：2025-01-15 14:30:25" />
              <el-button @click="convertDateTimeToTimestamp" type="primary">转换成Unix时间戳</el-button>
              <el-input v-model="timestampForm.dateTimeResult" readonly placeholder="Unix时间戳结果" />
              <el-select v-model="timestampForm.dateTimeUnit" style="width: 80px">
                <el-option label="秒" value="seconds" />
                <el-option label="毫秒" value="milliseconds" />
              </el-select>
            </div>
          </div>

          <!-- 详细日期时间输入转Unix时间戳 -->
          <div class="timestamp-section">
            <h3>时间</h3>
            <div class="detailed-time-input">
              <div class="time-input-group">
                <el-input v-model="timestampForm.year" placeholder="年" style="width: 80px" />
                <span class="time-label">年</span>
                <el-input v-model="timestampForm.month" placeholder="月" style="width: 60px" />
                <span class="time-label">月</span>
                <el-input v-model="timestampForm.day" placeholder="日" style="width: 60px" />
                <span class="time-label">日</span>
                <el-input v-model="timestampForm.hour" placeholder="时" style="width: 60px" />
                <span class="time-label">时</span>
                <el-input v-model="timestampForm.minute" placeholder="分" style="width: 60px" />
                <span class="time-label">分</span>
                <el-input v-model="timestampForm.second" placeholder="秒" style="width: 60px" />
                <span class="time-label">秒</span>
              </div>
              <div class="detailed-conversion">
                <el-button @click="convertDetailedTimeToTimestamp" type="primary">转换Unix时间戳</el-button>
                <el-input v-model="timestampForm.detailedResult" readonly placeholder="Unix时间戳结果" />
                <el-select v-model="timestampForm.detailedUnit" style="width: 80px">
                  <el-option label="秒" value="seconds" />
                  <el-option label="毫秒" value="milliseconds" />
                </el-select>
              </div>
            </div>
          </div>
        </el-card>
      </el-tab-pane>

      <!-- UTF-8编码 -->
      <el-tab-pane label="UTF-8编码" name="utf8">
        <el-card>
          <el-form :model="utf8Form" label-width="100px">
            <el-form-item label="操作类型">
              <el-radio-group v-model="utf8Form.mode" @change="handleUtf8">
                <el-radio label="encode">编码</el-radio>
                <el-radio label="decode">解码</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="输入内容">
              <el-input
                v-model="utf8Form.input"
                type="textarea"
                :rows="4"
                :placeholder="utf8Form.mode === 'encode' ? '请输入要编码的文本' : '请输入要解码的UTF-8字符串'"
                @input="handleUtf8"
              />
            </el-form-item>
            <el-form-item label="输出结果">
              <el-input
                v-model="utf8Form.output"
                type="textarea"
                :rows="4"
                readonly
                :placeholder="utf8Form.mode === 'encode' ? 'UTF-8编码结果' : '解码结果'"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="copyToClipboard(utf8Form.output)">
                复制结果
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- 二维码 -->
      <el-tab-pane label="二维码生成/解码" name="qrcode">
        <el-card>
          <el-form :model="qrcodeForm" label-width="100px">
            <el-form-item label="操作类型">
              <el-radio-group v-model="qrcodeForm.mode" @change="handleQrCode">
                <el-radio label="generate">生成</el-radio>
                <el-radio label="decode">解码</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="输入内容">
              <el-input
                v-model="qrcodeForm.input"
                type="textarea"
                :rows="4"
                :placeholder="qrcodeForm.mode === 'generate' ? '请输入要生成二维码的文本' : '请上传二维码图片'"
                @input="handleQrCode"
              />
            </el-form-item>
            <el-form-item v-if="qrcodeForm.mode === 'decode'" label="上传图片">
              <el-upload
                class="upload-demo"
                drag
                :auto-upload="false"
                :on-change="handleFileChange"
                accept="image/*"
              >
                <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item v-if="qrcodeForm.mode === 'generate' && qrcodeForm.qrCodeUrl" label="二维码">
              <div style="text-align: center;">
                <img :src="qrcodeForm.qrCodeUrl" alt="二维码" style="max-width: 200px;" />
              </div>
            </el-form-item>
            <el-form-item v-if="qrcodeForm.mode === 'decode'" label="解码结果">
              <el-input
                v-model="qrcodeForm.output"
                type="textarea"
                :rows="3"
                readonly
                placeholder="解码结果将在这里显示"
              />
            </el-form-item>
            <el-form-item>
              <el-button v-if="qrcodeForm.mode === 'generate'" type="primary" @click="downloadQrCode">
                下载二维码
              </el-button>
              <el-button v-if="qrcodeForm.mode === 'decode'" type="primary" @click="copyToClipboard(qrcodeForm.output)">
                复制结果
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, UploadFilled } from '@element-plus/icons-vue'
import QRCode from 'qrcode'
import jsQR from 'jsqr'
import dayjs from 'dayjs'

const route = useRoute()
const activeTab = ref('unicode')

// Unicode表单
const unicodeForm = reactive({
  input: '',
  output: '',
  mode: 'encode'
})

// 时间戳表单
const timestampForm = reactive({
  current: '',
  input: '',
  output: '',
  timestampInput: '',
  timestampResult: '',
  dateTimeInput: '',
  dateTimeResult: '',
  year: '',
  month: '',
  day: '',
  hour: '',
  minute: '',
  second: '',
  detailedResult: '',
  timestampUnit: 'seconds',
  dateTimeUnit: 'seconds',
  detailedUnit: 'seconds',
  isRunning: false
})

// UTF-8表单
const utf8Form = reactive({
  input: '',
  output: '',
  mode: 'encode'
})

// 二维码表单
const qrcodeForm = reactive({
  input: '',
  output: '',
  mode: 'generate',
  qrCodeUrl: ''
})

// 根据URL参数设置活动标签页
onMounted(() => {
  const tab = route.query.tab
  if (tab && ['unicode', 'timestamp', 'utf8', 'qrcode'].includes(tab)) {
    activeTab.value = tab
  }
  
  // 初始化时间戳表单
  const now = new Date()
  timestampForm.year = now.getFullYear().toString()
  getCurrentTimestamp()
  
  // 自动开始时间戳更新
  startTimestampUpdate()
})

// 处理Unicode编码
const handleUnicode = () => {
  if (!unicodeForm.input) {
    unicodeForm.output = ''
    return
  }
  
  try {
    if (unicodeForm.mode === 'encode') {
      unicodeForm.output = unicodeForm.input.split('').map(char => {
        return '\\u' + char.charCodeAt(0).toString(16).padStart(4, '0')
      }).join('')
    } else {
      unicodeForm.output = unicodeForm.input.replace(/\\u([0-9a-fA-F]{4})/g, (match, hex) => {
        return String.fromCharCode(parseInt(hex, 16))
      })
    }
  } catch (error) {
    unicodeForm.output = '处理失败，请检查输入格式'
  }
}

// 获取当前时间戳
const getCurrentTimestamp = () => {
  timestampForm.current = Math.floor(Date.now() / 1000).toString()
}

// 刷新当前时间戳
const refreshTimestamp = () => {
  getCurrentTimestamp()
}

// 开始/停止时间戳更新
const startTimestampUpdate = () => {
  if (timestampForm.isRunning) {
    clearInterval(timestampForm.updateInterval)
    timestampForm.isRunning = false
  } else {
    getCurrentTimestamp()
    timestampForm.updateInterval = setInterval(getCurrentTimestamp, 1000) // 每秒更新一次
    timestampForm.isRunning = true
  }
}

// Unix时间戳转日期时间
const convertTimestampToDate = () => {
  if (!timestampForm.timestampInput) {
    timestampForm.timestampResult = ''
    return
  }
  try {
    const timestamp = parseInt(timestampForm.timestampInput)
    const milliseconds = timestampForm.timestampUnit === 'seconds' ? timestamp * 1000 : timestamp
    const date = new Date(milliseconds)
    const unit = timestampForm.timestampUnit === 'seconds' ? '秒' : '毫秒'
    timestampForm.timestampResult = ` ${dayjs(date).format('YYYY-MM-DD HH:mm:ss')}`
  } catch (error) {
    timestampForm.timestampResult = '转换失败，请检查输入格式'
  }
}

// 日期时间转Unix时间戳（简化版）
const convertDateTimeToTimestamp = () => {
  if (!timestampForm.dateTimeInput) {
    timestampForm.dateTimeResult = ''
    return
  }
  try {
    const date = dayjs(timestampForm.dateTimeInput)
    if (!date.isValid()) {
      timestampForm.dateTimeResult = '无效的日期时间格式'
      return
    }
    const milliseconds = date.valueOf()
    const timestamp = timestampForm.dateTimeUnit === 'seconds' ? Math.floor(milliseconds / 1000) : milliseconds
    timestampForm.dateTimeResult = `${timestamp}`
  } catch (error) {
    timestampForm.dateTimeResult = '转换失败，请检查输入格式'
  }
}

// 详细日期时间输入转Unix时间戳
const convertDetailedTimeToTimestamp = () => {
  if (!timestampForm.year || !timestampForm.month || !timestampForm.day || !timestampForm.hour || !timestampForm.minute || !timestampForm.second) {
    timestampForm.detailedResult = ''
    return
  }
  try {
    const date = dayjs(`${timestampForm.year}-${timestampForm.month}-${timestampForm.day} ${timestampForm.hour}:${timestampForm.minute}:${timestampForm.second}`)
    if (!date.isValid()) {
      timestampForm.detailedResult = '无效的日期时间格式'
      return
    }
    const milliseconds = date.valueOf()
    const timestamp = timestampForm.detailedUnit === 'seconds' ? Math.floor(milliseconds / 1000) : milliseconds
    const unit = timestampForm.detailedUnit === 'seconds' ? '秒' : '毫秒'
    timestampForm.detailedResult = ` ${timestamp}`
  } catch (error) {
    timestampForm.detailedResult = '转换失败，请检查输入格式'
  }
}

// 处理UTF-8编码
const handleUtf8 = () => {
  if (!utf8Form.input) {
    utf8Form.output = ''
    return
  }
  
  try {
    if (utf8Form.mode === 'encode') {
      utf8Form.output = Array.from(utf8Form.input).map(char => {
        return char.charCodeAt(0).toString(16).padStart(4, '0')
      }).join(' ')
    } else {
      utf8Form.output = utf8Form.input.split(' ').map(hex => {
        return String.fromCharCode(parseInt(hex, 16))
      }).join('')
    }
  } catch (error) {
    utf8Form.output = '处理失败，请检查输入格式'
  }
}

// 处理二维码
const handleQrCode = async () => {
  if (qrcodeForm.mode === 'generate' && qrcodeForm.input) {
    try {
      qrcodeForm.qrCodeUrl = await QRCode.toDataURL(qrcodeForm.input)
    } catch (error) {
      ElMessage.error('生成二维码失败')
    }
  }
}

// 处理文件上传
const handleFileChange = (file) => {
  if (file.raw) {
    const reader = new FileReader()
    reader.onload = (e) => {
      const img = new Image()
      img.onload = () => {
        try {
          // 创建canvas来获取图像数据
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')
          canvas.width = img.width
          canvas.height = img.height
          ctx.drawImage(img, 0, 0)
          
          // 获取图像数据
          const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
          
          // 使用jsQR解码二维码
          const code = jsQR(imageData.data, imageData.width, imageData.height)
          
          if (code) {
            qrcodeForm.output = `解码成功！\n二维码内容：\n${code.data}`
          } else {
            qrcodeForm.output = '未能识别二维码，请确保上传的是有效的二维码图片'
          }
        } catch (error) {
          console.error('二维码解码错误:', error)
          qrcodeForm.output = '解码失败，请检查图片格式是否正确'
        }
      }
      img.onerror = () => {
        qrcodeForm.output = '图片加载失败，请检查文件格式'
      }
      img.src = e.target.result
    }
    reader.readAsDataURL(file.raw)
  }
}

// 下载二维码
const downloadQrCode = () => {
  if (qrcodeForm.qrCodeUrl) {
    const link = document.createElement('a')
    link.download = 'qrcode.png'
    link.href = qrcodeForm.qrCodeUrl
    link.click()
  }
}

// 复制到剪贴板
const copyToClipboard = async (text) => {
  if (!text) {
    ElMessage.warning('没有内容可复制')
    return
  }
  
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('复制成功')
  } catch (error) {
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('复制成功')
  }
}

// 复制当前时间戳
const copyCurrentTimestamp = () => {
  copyToClipboard(timestampForm.current)
}

</script>

<style scoped>
.encode-page {
  max-width: 1000px;
  margin: 0 auto;
}

.el-tabs {
  margin-top: 20px;
}

.upload-demo {
  width: 100%;
}

.timestamp-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.timestamp-section h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
  font-size: 16px;
}

.current-timestamp .el-input {
  width: 100%;
}

.current-timestamp .el-input__inner {
  color: #f56c6c;
  font-weight: bold;
}

.conversion-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
  flex-wrap: wrap;
}

.conversion-row .el-input {
  flex: 1;
  min-width: 200px;
}

.conversion-row .el-select {
  width: 80px;
}

.conversion-row .el-button {
  flex-shrink: 0;
  white-space: nowrap;
}

.detailed-time-input {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-top: 10px;
}

.time-input-group {
  display: flex;
  align-items: center;
  gap: 5px;
  flex-wrap: wrap;
}

.time-input-group .el-input {
  width: 80px;
}

.time-input-group .el-input:nth-child(1) {
  width: 100px;
}

.time-input-group .time-label {
  font-size: 14px;
  color: #606266;
  margin-right: 5px;
}

.detailed-conversion {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.detailed-conversion .el-input {
  flex: 1;
  min-width: 200px;
}

.detailed-conversion .el-select {
  width: 80px;
}
</style> 